var bkm = bkm || {};

(function () {
    'use strict';
    bkm.bank = bkm.bank || {};
    return bkm;
})();

(function () {
    'use strict';
    const _bankCardBinCacheKey = "BankCardBinCacheKey";
    let _bankcardList = JSON.parse(bkm.util.getItem(_bankCardBinCacheKey)) || [];
    // 先使用缓存的数据
    if (_bankcardList.length === 0) {
        let xhttp;
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //调用open()方法建立与服务器的连接
        xhttp.open('post', '/api/services/app/Bank/GetAllBankCardBins', true);
        //设置请求头信息
        xhttp.setRequestHeader('Content-Type', 'application/json');
        xhttp.setRequestHeader('Accept', 'application/json, text/plain, */*');
        //设置请求-响应状态发生改变时的回调函数
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {//请求-响应成功完成
                //获取响应信息
                let res = JSON.parse(xhttp.responseText);
                let dataItems = res.result.items;
                bkm.bank.initBankcardList(dataItems);
            }
        }
        //向服务器发送请求
        xhttp.send();
    }

    /** 根据后端返回的结果集初始化bankcardList变量 */
    bkm.bank.initBankcardList = function (reponseItems) {
        let list = [];
        let listItem, cardBinItems, cardBinItemKey, regStr, cardLength;
        reponseItems.forEach(item => {
            listItem = { bankName: item.bankName, bankCode: item.bankCode, cnapsCode: item.cnapsCode, bankNo: item.bankNo, patterns: [] };
            list.push(listItem);
            cardBinItems = {};
            item.bankCardBins.forEach(cardBinItem => {
                cardBinItemKey = (cardBinItem.cardLength - cardBinItem.cardBin.length) + '_' + cardBinItem.cardType;
                if (!cardBinItems[cardBinItemKey]) {
                    cardBinItems[cardBinItemKey] = {
                        cardBins: [cardBinItem.cardBin],
                        cardType: cardBinItem.cardType
                    };
                } else {
                    cardBinItems[cardBinItemKey].cardBins.push(cardBinItem.cardBin);
                }
            });
            for (let cItem in cardBinItems) {
                cardLength = parseInt(cItem.split('_')[0]);
                regStr = "^(" + cardBinItems[cItem].cardBins.join('|') + ")[0-9]{" + cardLength + "}$";
                listItem.patterns.push({
                    reg: regStr,
                    cardType: cardBinItems[cItem].cardType
                });
            }
        });
        // 缓存银行卡bin数据
        const defaultTTL = 10 * 3600; // 过期时间为 10 小时;
        bkm.util.setItem(_bankCardBinCacheKey, JSON.stringify(list), defaultTTL);
        _bankcardList.splice.apply(_bankcardList, [0, _bankcardList.length].concat(list));
    }

    bkm.bank.getBankNameByCode = function (bankCode) {
        var found = _bankcardList.filter(item => item.bankCode == bankCode);
        return found.length > 0 ? found[0].bankName : "";
    };
    bkm.bank.getBankInfoByCode = function (bankCode) {
        var found = _bankcardList.filter(item => item.bankCode == bankCode);
        return found.length > 0 ? found[0] : null;
    }
    bkm.bank._bankcardList = _bankcardList;
    bkm.bank.getBankInfoByNo = function (cardNo) {
        var cardTypeMap = {
            DC: "储蓄卡",
            CC: "信用卡",
            SCC: "准贷记卡",
            PC: "预付费卡"
        };

        function extend(target, source) {
            var result = {};
            var key;
            target = target || {};
            source = source || {};
            for (key in target) {
                if (target.hasOwnProperty(key)) {
                    result[key] = target[key];
                }
            }
            for (key in source) {
                if (source.hasOwnProperty(key)) {
                    result[key] = source[key];
                }
            }
            return result;
        }

        function getCardTypeName(cardType) {
            if (cardTypeMap[cardType]) {
                return cardTypeMap[cardType];
            }
            return null;
        }

        function _getBankInfoByCardNo(bankcardNo) {
            var cardTypeEnums = [{ key: 0, value: 'DC' }, { key: 1, value: 'CC' }, { key: 2, value: 'SCC' }, { key: 3, value: 'PC' }];
            for (var i = 0, len = _bankcardList.length; i < len; i++) {
                var bankcard = _bankcardList[i];
                var patterns = bankcard.patterns;
                for (var j = 0, jLen = patterns.length; j < jLen; j++) {
                    var pattern = patterns[j];
                    if ((new RegExp(pattern.reg, 'g')).test(bankcardNo)) {
                        var info = extend(bankcard, pattern);
                        info.bankCardType = info.cardType;
                        var found = cardTypeEnums.filter((elem) => elem.value == info.cardType);
                        info.bankCardEnumType = found.length > 0 ? found[0].key : null;
                        delete info.patterns;
                        delete info.reg;
                        info.cardTypeName = getCardTypeName(info.cardType);
                        return info; //返回银行卡结果
                    }
                }
            }
            return null;
        }
        return _getBankInfoByCardNo(cardNo);
    };

})();